#include "../include/type.h"
#include"../include/server.h"

#define DATABASE "mydatabase"

int datbas_open(sqlite3 **db)
{
	char        *errmsg;

	if(sqlite3_open(DATABASE,db)!=SQLITE_OK)//创建或打开数据库
	{

		printf("sqlite3_open error:%s\n",sqlite3_errmsg(*db));
        return -1;
	}

	printf("sqlite3_open success.\n");

	//判断数据库中的表是否存在，如果不存在则创建表
	if(sqlite3_exec(*db,"create table if not exists tempreature (date varchar,time varchar,ID varchar,temp varchar);",NULL,NULL,&errmsg)!=SQLITE_OK)
	{
		printf("Create failed:%s\n",errmsg);
        return -1;
	}
    printf("Open table tempreature successfully!\n");

	return 0;
}

int datbas_insert(sqlite3 *db,u8 *date,u8 *time,u8 *ID,u8 *temp)
{
	char        *errmsg;

	char        sql[128];

	if(!db)
	{
		printf("Invalid input argument db!\n");
		return -1;
	}

	memset(sql,0,sizeof(sql)); 
	if(snprintf(sql, sizeof(sql), "insert into tempreature values('%s','%s','%s','%s');",date,time,ID,temp)<0)
	{
		printf("sprintf error:%s\n",strerror(errno));
		return -1;
	}

	printf("sql: [%s]\n",sql);

	if((sqlite3_exec(db,sql,NULL,NULL,&errmsg)) != SQLITE_OK)
	{ 
		printf("insert data into database failed:%s\n",errmsg);
		return -1;
	}
	printf("insert data into database successfully\n");     

	return 0;
}


int datbas_close(sqlite3 *db)
{

	if(sqlite3_close(db)!=SQLITE_OK)
	{
		printf("close database error:%s\n",sqlite3_errmsg(db));
		return -1;
	}

	return 0;

}


/*功能：将接收到的数据保存至数据库中
 *参数：
 *返回值：成功返回0，失败返回-1*/

int save_into_dbs(pack_t *pp)
{
    sqlite3             *db;
    int                 rv = -1;

    rv = datbas_open(&db);
    if(rv < 0)
    {
        return -1;
    }

    rv = datbas_insert(db,pp->date,pp->time,pp->ID,pp->temp);
    if(rv < 0)
    {
        return -1;
    }

    rv = datbas_close(db);
    if(rv < 0)
    {
        return -1;
    }

    return 0;

}
